<template>
  <a-modal :width="650" :visible="visible" title="批量上传" cancel-text="取消" ok-text="保存"
           @cancel="onCancel"
           @ok="onSave"
           :maskClosable="false"
           :bodyStyle="{maxHeight:'450px',overflow:'scroll'}"
           destroy-on-close>
    <a-table :columns="columns" :data-source="uploadList"
             :pagination="false" bordered>
      <template #bodyCell="{column,record,index}">
        <template v-if="column.key=='name'">
          <a-input v-model:value="record.name" :maxlength="20"
                   :disabled="!record.response?.data?.fileUrl"></a-input>
        </template>
        <template v-if="column.key=='process'">
          <a-progress :percent="record.percent"/>
        </template>
        <template v-if="column.key=='action'">
          <a-space>
            <a-tooltip>
              <template #title>在线预览</template>
              <a-button
                  type="link"
                  @click="previewClick(record)"
                  :disabled="!record.response?.data?.fileUrl"
              >
                <template #icon>
                  <EyeOutlined/>
                </template>
              </a-button>
            </a-tooltip>
            <a-tooltip>
              <template #title>删除</template>
              <a-button
                  type="text"
                  @click="deleteItem(index)"
              >
                <template #icon>
                  <DeleteOutlined class="del-icon"/>
                </template>
              </a-button>

            </a-tooltip>
          </a-space>

        </template>
      </template>
    </a-table>

    <!-- 预览附件 -->
    <electronContractModal
        :visible="electronContractVisible"
        :esignDetail="{
        esignCheck: true,
      }"
        @close="electronContractVisible = false"
        @refresh="electronContractVisible = false"
        type="contractDetail"
        title="在线预览"
        :urlData="previewUrlData"
    />

    <!-- 预览图片 -->
    <PreviewImg
        :visible="imgVisible"
        :index="0"
        :list="imgList"
        @close="imgVisible = false"
    />

  </a-modal>
</template>

<script>
import {Modal, message} from "ant-design-vue";
import {DeleteOutlined, ExclamationCircleOutlined, EyeOutlined} from "@ant-design/icons-vue"
import {createVNode, watch, reactive, toRefs, ref} from "vue"
import request from '@/common/utils/request'
import {PreviewImg} from "bl-common-vue3";
import electronContractModal from '@/components/ElectronContractModal/index.vue'

export default {
  components: {electronContractModal, EyeOutlined, DeleteOutlined, PreviewImg},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    fileList: {
      type: Array,
      default: () => ([])
    },
    params: {
      type: Object,
      default: () => {
        return {
          annex_type: 1,
          parent_id: 0,
        };
      },
    },
  },
  setup(props, context) {

    const state = reactive({
      uploadList: []
    })
    const onCancel = () => {
      Modal.confirm({
        title: '您确定取消吗？',
        icon: createVNode(ExclamationCircleOutlined),
        onOk() {
          context.emit("handleCancel")
        },
        onCancel() {
        },
      });
    }

    const onSave = () => {
      if (state.uploadList.length == 0) {
        message.error("请选择文件并等待上传完成后保存！")
        return
      }
      let isAllUpload = true
      state.uploadList.forEach(item => {
        if (!item.response?.data?.fileUrl) {
          isAllUpload = false
        }
      })
      if (!isAllUpload) {
        message.error("请等待所有文件上传完成或删除未完成文件后保存！")
        return
      }
      let haveEmpty = false
      state.uploadList.forEach(item => {
        if (item.name.length == 0) {
          haveEmpty = true
        }
      })
      if (haveEmpty) {
        message.error("请输入文件名称后保存！")
        return
      }

      for (let i = 0; i < state.uploadList.length; i++) {
        const item = state.uploadList[i];
        const params = {
          name: item.name,
          annex_source: 1,
          file_path: item.response.data.fileUrl,
          needMsg: true,
        };
        for (let key in props.params) {
          if (props.params[key]) {
            params[key] = props.params[key];
          }
        }
        params.annex_type = 2; //文件上传
        request
            .post("/org", `/${params.typeFrom}/annexAdd`, params)
            .then(res => {
              if (i == state.uploadList.length - 1) {
                message.success("保存成功")
                context.emit("handleCommit")
              }
            })
      }
    }

    const deleteItem = (index) => {
      state.uploadList.splice(index, 1)
    }

    watch(() => props.fileList, (value) => {
      state.uploadList = value.map(item => {
        return {
          ...item,
          name: item.name.length > 19 ? item.name.substring(0, 19) : item.name
        }
      })
    })

    // 在线预览
    const imgVisible = ref(false);
    const imgList = ref([]);
    const electronContractVisible = ref(false);
    const previewUrlData = ref({});
    const previewClick = (record) => {
      // console.log(record)
      if (record.type.startsWith("image")) {
        imgList.value = [record.response.data.fileUrl];
        imgVisible.value = true;
      } else {
        previewUrlData.value = {
          url: record.response.data.fileUrl,
          previewUrl: record.response.data.previewUrl,
        };
        electronContractVisible.value = true;
      }
    };


    const columns = [
      {
        title: "文件名",
        key: "name",
      }, {
        title: "进度",
        key: "process",
        width: 200
      },
      {
        title: "操作",
        key: "action",
        align: "center",
        width: 100
      },

    ]

    return {
      ...toRefs(state),
      onCancel,
      onSave,
      columns,
      deleteItem,
      previewClick,
      electronContractVisible,
      previewUrlData,
      imgVisible,
      imgList
    }
  }
}
</script>

<style lang="less" scoped>
.del-icon {
  color: red;
  cursor: pointer;
}
</style>